package net.huashitong.nodeFile.controller;

import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.entity.NodeNewtemplet;
import net.huashitong.node.filter.NodeNewtempletFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.service.NodeNewtempletService;
import net.huashitong.node.utile.DateUtil;
import net.huashitong.nodeFile.entity.SysBnpFile;
import net.huashitong.nodeFile.service.SysBnpFileService;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static net.huashitong.Project.util.HolidayUtils.calLeaveDays;

/**
 * 文件上传下载
 * Created by hyp1202 on 2018/7/16.
 */
@Controller
@RequestMapping("/upLoad")
public class UpLoadController {
    @Autowired
    private SysBnpFileService fileservice;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private NodeNewtempletService nodeNewtempletService;
    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private MessageService ms;
    @Autowired
    private MessageUtil mu;
    @Autowired
    private SupervisionTaskService supervisionTaskService;

    //文件上传
    @ResponseBody
    @RequestMapping("/uploadBatch")
    public Message uplaodfile(@RequestParam MultipartFile files, String sysId, String projectId, HttpServletRequest request) {

        if (files == null) {
            return null;
        }
        Map<String, Object> mao = new HashMap<String, Object>();
        try {
            SysBnpFile sysBnpFile = new SysBnpFile();
            fileservice.saveFile(sysBnpFile, files);
            if (projectId == null || "".equals(projectId)) {
                String id = request.getParameter("sysId");
                BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
                NodeNewtempletFilter filter = new NodeNewtempletFilter();
                filter.setOperatorUser(user.getName());
                filter.setNodeId(id);
                List<NodeNewtemplet> nodeNewtempletList = nodeNewtempletService.getNodeForAcc(filter);
                for (NodeNewtemplet nodeNewtemplet : nodeNewtempletList) {
                    nodeNewtemplet.setNodeFilter(sysBnpFile.getSysId());
                    nodeNewtempletService.update(nodeNewtemplet);
                }
            } else {
                NodeNewschedules nodeNewschedules = nodeNewschedulesService.getNodeNewschedulesByProjectIdAndNodeId(projectId, sysId);
                nodeNewschedules.setNodeFilter(sysBnpFile.getSysId());
                nodeNewschedulesService.update(nodeNewschedules);
            }

            mao.put("sysid", sysBnpFile.getSysId());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return coverMessage("200", "successful", mao);
    }


    /**
     * 业主单位
     * 文件上传
     *
     * @param files
     * @param nodeSysId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/upload")
    public Message uplaod(@RequestParam MultipartFile files, String nodeSysId, HttpServletRequest request) throws ParseException {
        if (files == null) {
            return null;
        }
        //节点完成->判断此时节点的进度（正常、逾期）并进入绩效考核得分里面
        NodeNewschedules nodeNewschedules = nodeNewschedulesService.getNodeOne(nodeSysId);
        String projectId = nodeNewschedules.getProjectId();
        String nodeId = nodeNewschedules.getNodeId();
        //根据projectId和nodeId查询督查任务
        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setProjectId(projectId);
        taskFilter.setNodeId(nodeId);
        List<SupervisionTask> tasks = supervisionTaskService.getTaskListsNoPage(taskFilter);
        for (SupervisionTask task : tasks) {
            task.setRespResult("1");
            //发短信给相关督查组，提醒办结任务
            mu.remindToDoTaskToSupervisionMessage(task);
        }
        supervisionTaskService.batchUpdate(tasks);

        String planBeginDate = nodeNewschedules.getPlanBeginDate();
        String planTime = nodeNewschedules.getPlanTime();
        String factFinishDate = DateUtil.getDate();
        NewProjects project = newProjectsService.getById(nodeNewschedules.getProjectId());
        //绩效考核得分
        GradePoint grade = new GradePoint();
        SimpleDateFormat myFmt = new SimpleDateFormat("yyyy.MM.dd");
        Date beginDate = myFmt.parse(StringUtils.isBlank(planBeginDate) ? factFinishDate : planBeginDate);
        Date finishDate = myFmt.parse(factFinishDate);
        //实际完成的天数(过滤周末)
        double t = calLeaveDays(beginDate, finishDate);
        int planTimeInt = Integer.parseInt(StringUtils.isBlank(planTime) ? "1" : planTime);
        //如果计划用时大于等于实际用时，则正常完成该节点（绩效得100分）
        if (Double.parseDouble(planTimeInt + "") >= t) {
            newProjectsService.updateFullMarkPoint(nodeNewschedules, project);
        }


        Map<String, Object> mao = new HashMap<>();
        try {
            SysBnpFile sysBnpFile = new SysBnpFile();
            fileservice.saveFile(sysBnpFile, files);

            nodeNewschedules.setNodeFilter(sysBnpFile.getSysId());
            nodeNewschedules.setStatus("2");
            nodeNewschedules.setFactFinishDate(DateUtil.getDate());

//            int factTime = betweenTwoDateNum(nodeNewschedules.getPlanBeginDate(), DateUtil.getDate()) + 1;

            nodeNewschedules.setFactTime((int) t + "");
            nodeNewschedulesService.update(nodeNewschedules);
            List<NodeNewschedules> list = nodeNewschedulesService.getNodelistByNodeId(nodeNewschedules.getNodeIds(), nodeNewschedules.getProjectId(), nodeNewschedules.getNodeId());
            if (list.size() != 0) {     //还有小节点未完成
                NodeNewschedules n = list.get(0);
                n.setStatus("1");   //下个小节点设置成开始状态
                n.setIsDelay("0");
                nodeNewschedulesService.update(n);

                //获取完成的小节点:     list0->所有确定的小节点
                List<NodeNewschedules> lists = nodeNewschedulesService.getListNodeIds(n.getNodeIds(), n.getProjectId());
                List<NodeNewschedules> list0 = nodeNewschedulesService.getNodeIdsList(n.getNodeIds(), n.getProjectId(), "");
                //判断所在节点小节点是否全部完成，
                //完成---大节点改为2-----
                if (list0.size() - lists.size() == 0) {
                    NodeNewschedules bigNns = nodeNewschedulesService.getNnsByProjectIdAndNodeId(n.getProjectId(), n.getNodeIds());
                    bigNns.setStatus("2");
                    bigNns.setFactFinishDate(DateUtil.getDate());

                    Date bigBeginDate = myFmt.parse(bigNns.getPlanBeginDate());
                    double c = calLeaveDays(bigBeginDate, finishDate);

//                    int factTimeBig = betweenTwoDateNum(bigNns.getPlanBeginDate(), DateUtil.getDate()) + 1;

                    bigNns.setFactTime((int) c + "");
                    nodeNewschedulesService.update(bigNns);
                    //根据前置
                    List<NodeNewschedules> lists1 = nodeNewschedulesService.getListByPreNodeId(bigNns.getProjectId(), bigNns.getNodeId());
                    if (ObjectUtils.isNotBlank(lists1)) {
                        for (NodeNewschedules nnss : lists1) {
                            nnss = nodeNewschedulesService.getById(nnss.getSysId());
                            List<NodeNewschedules> lists2 = nodeNewschedulesService.getListByPreNodeId2(nnss.getPreNodeId(), nnss.getProjectId());
                            if (ObjectUtils.isNotBlank(lists2)) {
                                int ss = 0;
                                for (NodeNewschedules nnss2 : lists2) {
                                    if ("2".equals(nnss2.getStatus())) {
                                        ss++;
                                    } else {
                                        break;
                                    }
                                }
                                if (lists2.size() == ss) {
                                    nnss.setStatus("1");
                                    nnss.setFactFinishDate(DateUtil.getDate());
                                    nodeNewschedulesService.update(nnss);
                                    NodeNewschedules smallNns = nodeNewschedulesService.getNnsByProjectIdAndNodeId(nnss.getProjectId(), nnss.getNodeId() + ".1");
                                    if (ObjectUtils.isNotBlank(smallNns)) {
                                        smallNns.setStatus("1");
                                        smallNns.setPlanBeginDate(DateUtil.getDate());
                                        nodeNewschedulesService.update(smallNns);
                                        NewProjects np = newProjectsService.getById(n.getProjectId());
                                        Map<String, Object> ma = mu.taskMessage(smallNns.getOperatorUser(), smallNns.getOperatorPhone(), "《" + np.getName() + "》", smallNns.getNodeId());
                                        if ("0".equals(ma.get("code").toString())) {
                                            net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                                            m.setRecipients(smallNns.getOperatorUser());
                                            m.setText(ma.get("text").toString());
                                            m.setType("1");
                                            m.setPhone(smallNns.getOperatorPhone());
                                            m.setMsg(ma.get("msg").toString());
                                            m.setProjectName(np.getName());
                                            m.setResDept(smallNns.getResDept());
                                            ms.save(m);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    //下一个小节点开始操作
                    if (ObjectUtils.isNotBlank(n)) {
                        n.setStatus("1");
                        n.setPlanBeginDate(DateUtil.getDate());
                        nodeNewschedulesService.update(n);
                        NewProjects np = newProjectsService.getById(n.getProjectId());
                        Map<String, Object> ma = mu.taskMessage(n.getOperatorUser(), n.getOperatorPhone(), "《" + np.getName() + "》", n.getNodeId());
                        if ("0".equals(ma.get("code").toString())) {
                            net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                            m.setRecipients(n.getOperatorUser());
                            m.setText(ma.get("text").toString());
                            m.setType("0");
                            m.setPhone(n.getOperatorPhone());
                            m.setMsg(ma.get("msg").toString());
                            m.setProjectName(np.getName());
                            m.setResDept(n.getResDept());
                            ms.save(m);
                        }
                    }
                }

            } else {
                //下一个大节点开始
                NodeNewschedules bigNns = nodeNewschedulesService.getNnsByProjectIdAndNodeId(nodeNewschedules.getProjectId(), nodeNewschedules.getNodeIds());
                bigNns.setStatus("2");
                bigNns.setFactFinishDate(DateUtil.getDate());
                nodeNewschedulesService.update(bigNns);
                //根据前置
                List<NodeNewschedules> lists1 = nodeNewschedulesService.getListByPreNodeId(bigNns.getProjectId(), bigNns.getNodeId());
                if (ObjectUtils.isNotBlank(lists1)) {
                    for (NodeNewschedules nnss : lists1) {
                        nnss = nodeNewschedulesService.getById(nnss.getSysId());
                        List<NodeNewschedules> lists2 = nodeNewschedulesService.getListByPreNodeId2(nnss.getPreNodeId(), nnss.getProjectId());
                        if (ObjectUtils.isNotBlank(lists2)) {
                            int ss = 0;
                            for (NodeNewschedules nnss2 : lists2) {
                                if ("2".equals(nnss2.getStatus())) {
                                    ss++;
                                } else {
                                    break;
                                }
                            }
                            if (lists2.size() == ss) {
                                nnss.setStatus("1");
                                nnss.setFactFinishDate(DateUtil.getDate());
                                nodeNewschedulesService.update(nnss);
                                NodeNewschedules smallNns = nodeNewschedulesService.getNnsByProjectIdAndNodeId(nnss.getProjectId(), nnss.getNodeId() + ".1");
                                if (ObjectUtils.isNotBlank(smallNns)) {
                                    smallNns.setStatus("1");
                                    smallNns.setPlanBeginDate(DateUtil.getDate());
                                    nodeNewschedulesService.update(smallNns);
                                    NewProjects np = newProjectsService.getById(nodeNewschedules.getProjectId());
                                    Map<String, Object> ma = mu.taskMessage(smallNns.getOperatorUser(), smallNns.getOperatorPhone(), "《" + np.getName() + "》", smallNns.getNodeId());
                                    if ("0".equals(ma.get("code").toString())) {
                                        net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                                        m.setRecipients(smallNns.getOperatorUser());
                                        m.setText(ma.get("text").toString());
                                        m.setType("1");
//                                    测试用
                                        m.setPhone(smallNns.getOperatorPhone());
                                        m.setMsg(ma.get("msg").toString());
                                        m.setProjectName(np.getName());
                                        m.setResDept(smallNns.getResDept());
                                        m.setNodeId(nodeNewschedules.getSysId());
                                        ms.save(m);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            mao.put("sysid", sysBnpFile.getSysId());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return coverMessage("200", "successful", mao);
    }

    //文件下载
    @RequestMapping(value = "/download/{id}")
    public void downLoad(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downLoadFileId(id, req, resp);
    }

    public void downLoadFileId(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {

        SysBnpFile sysBnpFile = null;
        NodeNewtemplet nodeNewtemplet = new NodeNewtemplet();
        List<NodeNewtemplet> list = nodeNewtempletService.queryByNodeFilter(fileId);

        if (list.size() != 0) {
            nodeNewtemplet = list.get(0);
            sysBnpFile = fileservice.getById(nodeNewtemplet.getNodeFilter());
        }


        if (sysBnpFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysBnpFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
            System.out.println("filepath=" + filepath);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
//            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        System.out.println("filepath2=" + Global.getUploadBaseDir() + filepath);
        try {
            resp.setHeader("Content-Type", "application/octet-stream");
            String nodeName = nodeNewtemplet.getNodeName() + "模板";
            String nanes = new String(nodeName.getBytes(), "iso8859-1");
            resp.setHeader("Content-Disposition", "attachment; filename=" + nanes + "." + sysBnpFile.getFileType());
            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());

            return;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }
    }


    /**
     * 文件下载
     *
     * @param id
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping(value = "/downloadFile/{id}")
    public void downLoadfile(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downLoadFile(id, req, resp);
    }

    public void downLoadFile(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {

        SysBnpFile sysBnpFile = fileservice.getById(fileId);
        if (sysBnpFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysBnpFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
            System.out.println("filepath=" + filepath);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
//            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        System.out.println("filepath2=" + Global.getUploadBaseDir() + filepath);
        try {
            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
            resp.setHeader("Content-Type", "application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename=" + sysBnpFile.getFilename() + "." + sysBnpFile.getFileType());
            return;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }
    }

    /**
     * 具体项目节点文件下载
     *
     * @param id
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping(value = "/downloadProjectFile/{id}")
    public void downProjectfile(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downProjectFile(id, req, resp);
    }

    public void downProjectFile(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        NodeNewschedules nodeNewschedules = nodeNewschedulesService.getNodeOne(fileId);
        NewProjects projects = newProjectsService.getById(nodeNewschedules.getProjectId());
        SysBnpFile sysBnpFile = fileservice.getById(nodeNewschedules.getNodeFilter());
        if (sysBnpFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysBnpFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
//            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        try {
            String nodeName = projects.getName() + ":" + nodeNewschedules.getNodeId() + nodeNewschedules.getNodeName();
            String n = new String(nodeName.getBytes(), "iso8859-1");
            resp.setHeader("Content-Type", "application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename=" + n + "." + sysBnpFile.getFileType());
            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
            return;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }
    }

    private Message coverMessage(String code, String msg, Object data) {
        Message message = new Message();
        message.setCode(code);
        message.setMessage(msg);
        message.setData(data);
        return message;
    }
}
